package com.carrental.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.carrental.entity.CarRental;
import com.carrental.util.DBConnection;

//汽车租赁订单数据操作
public class CarRentalDao {
	
	DBConnection dbConnection;
	
	//添加订单
	public int add(CarRental carRental) throws Exception {
		dbConnection = new DBConnection();
		String sql = "insert into car_rental(id,username,car_id,rental_num,rental_total,rental_start_datetime,rental_end_datetime,create_datetime) values(?,?,?,?,?,?,?,?)";
		int res = 0;
		res = dbConnection.executeUpdate(sql, new String[] {
				carRental.getId(), carRental.getUsername(), carRental.getCarId(), carRental.getRentalNum()+"", carRental.getRentalTotal()+"", carRental.getRentalStartDatetime().toString(),
				carRental.getRentalEndDatetime().toString(), carRental.getCreateDatetime().toString()
		});
		dbConnection.closeAll();
		return res;
	}
	
	//查询所有汽车订单
	public List<CarRental> selectAll() throws Exception {
		dbConnection = new DBConnection();
		String sql = "select * from car_rental";
		ResultSet res = dbConnection.executeQuery(sql);
		List<CarRental> list = new ArrayList<CarRental>();
		while (res.next()) {
			CarRental carRental = new CarRental();
			carRental.setId(res.getString("id"));
			carRental.setUsername(res.getString("username"));
			carRental.setCarId(res.getString("car_id"));
			carRental.setRentalNum(res.getInt("rental_num"));
			carRental.setRentalTotal(res.getDouble("rental_total"));
			carRental.setRentalStartDatetime(res.getDate("rental_start_datetime"));
			carRental.setRentalEndDatetime(res.getDate("rental_end_datetime"));
			carRental.setCreateDatetime(res.getTimestamp("create_datetime"));
			list.add(carRental);
		}
		dbConnection.closeAll();
		return list;
	}
	
	//根据用户名查询汽车订单
	public List<CarRental> selectByUsername(String username) throws Exception {
		dbConnection = new DBConnection();
		String sql = "select * from car_rental where username = ?";
		ResultSet res = dbConnection.executeQuery(sql, new String[] {username});
		List<CarRental> list = new ArrayList<CarRental>();
		while (res.next()) {
			CarRental carRental = new CarRental();
			carRental.setId(res.getString("id"));
			carRental.setUsername(res.getString("username"));
			carRental.setCarId(res.getString("car_id"));
			carRental.setRentalNum(res.getInt("rental_num"));
			carRental.setRentalTotal(res.getDouble("rental_total"));
			carRental.setRentalStartDatetime(res.getDate("rental_start_datetime"));
			carRental.setRentalEndDatetime(res.getDate("rental_end_datetime"));
			carRental.setCreateDatetime(res.getTimestamp("create_datetime"));
			list.add(carRental);
		}
		dbConnection.closeAll();
		return list;
	}

}
